package com.example.healkep;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HealthActivity extends AppCompatActivity {

    private static String show;
    private final String username = LoginActivity.getUser();
    private final String sessionid = LoginActivity.getSessionID();
    String[] disarray = new String[1000];

    public static String getShow() {
        return show;
    }

    public static void setShow(String show) {
        HealthActivity.show = show;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health);
        Spinner disease = findViewById(R.id.choosedisease);
        Button add = findViewById(R.id.add12);
        TextView diseasesget = findViewById(R.id.getdiseases);
        TextView diseasesshow = findViewById(R.id.showdiseases);
        EditText searchd = findViewById(R.id.searchd);
        Button update = findViewById(R.id.updatediseases);
        Button search = findViewById(R.id.searchdfrommysql);
        Button get = findViewById(R.id.togetdiseases);
        HashMap<String, String> record = new HashMap<>();

        add.setOnClickListener(view -> {
            if (getShow() == null) {
                if (Objects.equals(record.get(disease.getSelectedItem().toString()), "true")) {//未添加过
                    setShow(disease.getSelectedItem().toString() + ";");
                    record.replace(disease.getSelectedItem().toString(), "false");
                }
            } else {
                if (Objects.equals(record.get(disease.getSelectedItem().toString()), "true")) {//未添加过
                    setShow(getShow() + disease.getSelectedItem().toString() + ";");
                    record.replace(disease.getSelectedItem().toString(), "false");
                }
            }
            diseasesshow.setText(getShow());
        });

        search.setOnClickListener(view -> {
            String name = searchd.getText().toString();
            String json = "{\n" +
                    "    \"name\":\"" + name + "\"\n" +
                    "}";
            new Thread(() -> {
                try {
                    OkHttpClient clientget = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(LoginActivity.url + "/diseases/get")
                            .addHeader("Cookie", sessionid)
                            .post(RequestBody.create(MediaType.parse("application/json"), json))
                            .build();
                    Response response = clientget.newCall(request).execute();
                    String resultget = Objects.requireNonNull(response.body()).string();
                    JSONArray jsonArray = new JSONArray(resultget);
                    for (int j = 0; j < jsonArray.length(); j++) {
                        String temp = jsonArray.getString(j);
                        temp = temp.substring(9);
                        temp = temp.replace("t", "");
                        temp = temp.replace("\\", "");
                        temp = temp.replace("}", "");
                        int len = temp.length();
                        temp = temp.substring(0, len - 1);
                        disarray[j] = temp;
                        record.put(temp, "true");
                    }
                } catch (Exception e) {
                    runOnUiThread(() -> Toast.makeText(HealthActivity.this, "获取异常", Toast.LENGTH_SHORT).show());
                }
            }).start();
            ArrayAdapter<String> adapter = new ArrayAdapter<>(HealthActivity.this, android.R.layout.simple_spinner_item, disarray);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            disease.setAdapter(adapter);
        });

        update.setOnClickListener(v -> {
            String username = LoginActivity.getUser();
            String json = "{\n" +
                    "    \"username\":\"" + username + "\",\n" +
                    "    \"diseases\":\"" + getShow() + "\"\n" +
                    "}";
            String json3 = "{\n" +
                    "    \"username\":\"" + username + "\"\n" +
                    "}";
            diseasesshow.setText(null);
            new Thread(() -> {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(LoginActivity.url + "/information/updatedis")
                            .addHeader("Cookie", sessionid)
                            .post(RequestBody.create(MediaType.parse("application/json"), json))
                            .build();
                    client.newCall(request).execute();
                    OkHttpClient client2 = new OkHttpClient();
                    Request request2 = new Request.Builder()
                            .url(LoginActivity.url + "/information/getdis")
                            .addHeader("Cookie", sessionid)
                            .post(RequestBody.create(MediaType.parse("application/json"), json3))
                            .build();
                    Response response = client2.newCall(request2).execute();
                    String result = Objects.requireNonNull(response.body()).string();
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.get("username").equals("!@#")) {
                        runOnUiThread(() -> Toast.makeText(HealthActivity.this, "登录超时,请重新登录", Toast.LENGTH_SHORT).show());
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setClass(HealthActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        if (getShow().equals(jsonObject.getString("diseases"))) {
                            runOnUiThread(() -> Toast.makeText(HealthActivity.this, "更新成功", Toast.LENGTH_SHORT).show());
                            diseasesshow.setText(getShow());
                        } else {
                            runOnUiThread(() -> Toast.makeText(HealthActivity.this, "更新失败", Toast.LENGTH_SHORT).show());
                        }
                        diseasesget.setText(jsonObject.get("diseases").toString());
                    }
                } catch (Exception e) {
                    runOnUiThread(() -> Toast.makeText(HealthActivity.this, "连接异常", Toast.LENGTH_SHORT).show());
                }
            }).start();
        });

        get.setOnClickListener(view -> {
            String username = LoginActivity.getUser();
            String json2 = "{\n" +
                    "    \"username\":\"" + username + "\"\n" +
                    "}";
            new Thread(() -> {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(LoginActivity.url + "/information/getdis")
                            .addHeader("Cookie", sessionid)
                            .post(RequestBody.create(MediaType.parse("application/json"), json2))
                            .build();
                    Response response = client.newCall(request).execute();
                    String result = Objects.requireNonNull(response.body()).string();
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.get("username").equals("!@#")) {
                        runOnUiThread(() -> Toast.makeText(HealthActivity.this, "登录超时,请重新登录", Toast.LENGTH_SHORT).show());
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setClass(HealthActivity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        runOnUiThread(() -> Toast.makeText(HealthActivity.this, "获取成功", Toast.LENGTH_SHORT).show());
                        diseasesget.setText(jsonObject.get("diseases").toString());
                    }
                } catch (Exception e) {
                    runOnUiThread(() -> Toast.makeText(HealthActivity.this, "连接异常", Toast.LENGTH_SHORT).show());
                }
            }).start();
        });
    }
}